#!/bin/bash

# 容器名称
container_name="filebrowser"

# 挂载目录列表
mount_list=(
    # "${HOME}/Documents"
)

# 传入的参数添加到挂载目录列表
for mount_dir in $@; do
    # mount_list+=(${mount_dir})
    echo "添加指定挂载目录：${mount_dir}"
    mount_list+=("${mount_dir}")
done

# 如果存在 ~/.filebrowser.txt 文件，则读取配置
if [ -f ~/.filebrowser.txt ]; then
    echo "添加[~/.filebrowser.txt]挂载目录："
    while read line; do
        # 如果读取到的行不在挂载目录列表中，则添加到挂载目录列表
        if [[ ! " ${mount_list[@]} " =~ " ${line} " ]]; then
            mount_list+=("${line}")
            echo "    ${line}"
        fi
    done <~/.filebrowser.txt
else
    # 如果不存在 ~/.filebrowser.txt 文件，则创建
    touch ~/.filebrowser.txt
fi

# 写入配置
echo "挂载目录列表："
for mount_dir in ${mount_list[@]}; do
    echo "    ${mount_dir}"

    # 如果 mount_dir 不在 ~/.filebrowser.txt 文件中，则写入
    if ! grep -q "${mount_dir}" ~/.filebrowser.txt; then
        echo "${mount_dir}" >>~/.filebrowser.txt
    fi

done

# 组装挂载参数
mount_param=""

for mount_dir in ${mount_list[@]}; do
    mount_param="${mount_param} -v ${mount_dir}:/root/workspace/${mount_dir}"
done

# 如果容器已经存在，则删除
if [ "$(docker ps -a | grep ${container_name})" ]; then
    docker stop ${container_name} >>/dev/null && docker rm ${container_name} >>/dev/null
fi

# 启动容器
docker run -it \
    --privileged \
    --net=host \
    --ipc=host \
    --pid=host \
    --restart=always \
    --name ${container_name} \
    ${mount_param} \
    -d rs:filebrowser
